import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/ConsignOrderVo.dart';
import '../my/StepsWidget.dart';

class EcyMyConsignmentOrderDetailPage extends EcyCommonBaseWidget {
  final String orderCode;
  final String type;

  EcyMyConsignmentOrderDetailPage(this.orderCode, this.type);

  @override
  _EcyMyConsignmentOrderDetailPageState createState() {
    return _EcyMyConsignmentOrderDetailPageState(
        this, this.orderCode, this.type);
  }
}

class _EcyMyConsignmentOrderDetailPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  final String orderCode;
  final String type;
  _EcyMyConsignmentOrderDetailPageState(
      EcyCommonBaseWidget vc, this.orderCode, this.type) {
    controller = vc;
  }

  int _currentStep = 1;
  ConsignOrderVo _consignOrderVo = ConsignOrderVo();
  String _title = "";

  bool _purchaserFlag = true;

  @override
  void initState() {
    super.initState();

    setState(() {
      _purchaserFlag = type == "1"; // 0:卖家、1:买家
    });

    _loadDetail();
  }

  Future<void> _loadDetail() async {
    try {
      var response = await EcyRequestbasemanager()
          .get("/app/api/app/consign/order/detail?orderCode=$orderCode", {});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          setState(() {
            _consignOrderVo = ConsignOrderVo.fromJson(response["data"]);

            if (!_purchaserFlag) {
              _title = _consignOrderVo.status == "0"
                  ? "买家已下单，请尽快将宝贝送至寄售点"
                  : _consignOrderVo.status == "1"
                      ? "已将宝贝送至寄售点，等待买家提货"
                      : _consignOrderVo.status == "2"
                          ? "交易已完成"
                          : "已取消";
            } else {
              _title = _consignOrderVo.status == "0"
                  ? "已下单，等待卖家将宝贝送至寄售点"
                  : _consignOrderVo.status == "1"
                      ? "卖家已将宝贝送至寄售点，请尽快提货"
                      : _consignOrderVo.status == "2"
                          ? "交易已完成"
                          : "已取消";
            }
            _currentStep = _consignOrderVo.status == "0"
                ? 0
                : _consignOrderVo.status == "1"
                    ? 1
                    : 2;
          });
        } else {
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
        }
      } else {}
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 已寄存
  void _orderDeposit(String orderCode) async {
    try {
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign/order/deposit", {"orderCode": orderCode});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _consignOrderVo.status = "1";
          _currentStep = 1;
        });
        EasyLoading.showToast("寄存成功", duration: const Duration(seconds: 1));
      } else {
        EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
            duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 取消订单
  void _orderCancel() async {
    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/order/cancel",
          {"orderCode": _consignOrderVo.orderCode});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _consignOrderVo.status = "3";
          _currentStep = 2;
        });
        EasyLoading.showToast("订单已取消", duration: const Duration(seconds: 1));
      } else {
        EasyLoading.showToast(commonResponse.msg ?? "请稍后再试", duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget avatar = Image.asset('assets/images/avatar.jpeg', width: 64);

    return Scaffold(
      appBar: AppBar(
        //导航栏
        backgroundColor: const Color(0xFFFFDFEF),
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        title: Text(
          '订单详情',
          style: TextStyle(
              fontFamily: "PingFang SC",
              fontWeight: FontWeight.w700,
              fontSize: 16.sp,
              color: const Color(0xFF262626)),
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFFFDFEF), Colors.white]),
          ),
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 8, bottom: 10),
                  child: Text(_title,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w600,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                ),
                const Padding(padding: EdgeInsets.only(bottom: 6)),
                Card(
                    color: Colors.white,
                    elevation: 0,
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width,
                      child: Padding(
                          padding: const EdgeInsets.only(top: 10, bottom: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text("提货码",
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w600,
                                      fontSize: 16.sp,
                                      color: const Color(0xFF262626))),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 6)),
                              Text(_consignOrderVo.pickCode ?? "***",
                                  style: const TextStyle(
                                      fontSize: 38,
                                      fontWeight: FontWeight.w500)),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 6)),
                              Text(
                                _purchaserFlag ? '请凭交易码前往取货' : '请凭交易码前往寄存',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w600,
                                    fontSize: 16.sp,
                                    color: const Color(0xFFEA4B9B)),
                              ),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 6)),
                              StepsWidget(currentIndex: _currentStep),
                            ],
                          )),
                    )),
                const Padding(padding: EdgeInsets.only(bottom: 6)),
                Card(
                    color: Colors.white,
                    elevation: 0,
                    child: SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: Padding(
                            padding: const EdgeInsets.symmetric(
                                vertical: 10, horizontal: 14),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(_consignOrderVo.shop?.name ?? "",
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF8C8C8C)),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis),
                                const Padding(
                                    padding:
                                        EdgeInsets.only(right: 10, bottom: 16)),
                                Text(_consignOrderVo.shop?.address ?? "",
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF8C8C8C)),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis),
                                const Padding(
                                    padding:
                                        EdgeInsets.only(right: 10, bottom: 16)),
                                RichText(
                                  text: TextSpan(children: [
                                    const WidgetSpan(
                                        child: Icon(Icons.access_time_outlined,
                                            size: 20,
                                            color: Color(0xFF8C8C8C))),
                                    WidgetSpan(
                                      child: Text(
                                          '营业时间 周一至周日 ${_consignOrderVo?.shop?.businessHoursStart?.substring(0, 5) ?? ""}~${_consignOrderVo.shop?.businessHoursEnd?.substring(0, 5) ?? ""}',
                                          style: TextStyle(
                                              fontFamily: "PingFang SC",
                                              fontWeight: FontWeight.w600,
                                              fontSize: 14.sp,
                                              color: const Color(0xFF8C8C8C)),
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis),
                                    ),
                                  ]),
                                ),
                              ],
                            )))),
                const Padding(padding: EdgeInsets.only(bottom: 3)),
                Card(
                    color: Colors.white,
                    elevation: 0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              height: 64.w,
                              width: 64.w,
                              child: ClipRRect(
                                  borderRadius: BorderRadius.circular(15.r),
                                  child: CachedNetworkImage(
                                    width: 64.w,
                                    height: 64.w,
                                    imageUrl: _consignOrderVo
                                            .consignProduct?.mainImageUrl ??
                                        "",
                                    imageBuilder: (context, imageProvider) =>
                                        Container(
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(15.r)),
                                          image: DecorationImage(
                                              image: imageProvider,
                                              fit: BoxFit.cover)),
                                    ),
                                    errorWidget: (context, url, error) =>
                                        avatar,
                                  )),
                            ),
                            Expanded(
                                child: SizedBox(
                              height: 80.0,
                              child: Column(
                                // spacing: 10,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(left: 10),
                                    child: Text(
                                        _consignOrderVo.consignProduct?.title ??
                                            "***",
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w600,
                                            fontSize: 16.sp,
                                            color: const Color(0xFF262626)),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(left: 10),
                                    child: Text(
                                      '￥${_consignOrderVo.consignProduct?.price ?? "***"}',
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w600,
                                          fontSize: 16.sp,
                                          color: Colors.redAccent),
                                    ),
                                  ),
                                ],
                              ),
                            )),
                          ],
                        ),
                        Padding(
                          padding:
                              const EdgeInsets.only(left: 8, right: 8, top: 10),
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                Expanded(
                                  flex: 1,
                                  child: Text(
                                    '订单编号',
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF8C8C8C)),
                                  ),
                                ),
                                Expanded(
                                  flex: 3,
                                  child: Align(
                                    alignment: Alignment.centerRight,
                                    child: Text(
                                      '${_consignOrderVo.orderCode}',
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w600,
                                          fontSize: 14.sp,
                                          color: const Color(0xFF8C8C8C)),
                                    ),
                                  ),
                                ),
                              ]),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(
                              left: 8, right: 8, top: 10, bottom: 10),
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  flex: 1,
                                  child: Text(
                                    '下单时间',
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF8C8C8C)),
                                  ),
                                ),
                                Expanded(
                                  flex: 3,
                                  child: Align(
                                    alignment: Alignment.centerRight,
                                    child: Text(
                                      '${_consignOrderVo.createTime?.replaceFirst("T", "")}',
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w600,
                                          fontSize: 14.sp,
                                          color: const Color(0xFF8C8C8C)),
                                    ),
                                  ),
                                ),
                              ]),
                        ),
                      ],
                    )),
              ],
            ),
          ),
        ),
      ),
      bottomNavigationBar: _purchaserFlag
          ? null
          : BottomAppBar(
              color: Colors.white,
              // shape: CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Expanded(
                    flex: 1,
                    child: Container(
                      height: 40.0,
                      padding: const EdgeInsets.only(left: 10),
                      child: _consignOrderVo.status == "0"
                          ? TextButton(
                              onPressed: () {
                                _orderDeposit(_consignOrderVo.orderCode!);
                              },
                              style: const ButtonStyle(
                                alignment: Alignment.center,
                                foregroundColor:
                                    WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                                side: WidgetStatePropertyAll(BorderSide(
                                    color: Color(0xFFEA4B9B), width: 1)),
                              ),
                              child: const Text(
                                '  已寄存  ',
                                style: TextStyle(
                                  height: 1,
                                  leadingDistribution: TextLeadingDistribution
                                      .even, // 设置leading策略
                                ),
                              ))
                          : _consignOrderVo.status == "1"
                              ? TextButton(
                                  onPressed: () async {
                                    bool? confirmFlag =
                                        await _showConfirmDialog("确定取消订单吗");
                                    if (confirmFlag != null && confirmFlag) {
                                      _orderCancel();
                                    }
                                  },
                                  style: const ButtonStyle(
                                    foregroundColor: WidgetStatePropertyAll(
                                        Color(0xFF262626)),
                                    side: WidgetStatePropertyAll(BorderSide(
                                        color: Color(0xFFBFBFBF), width: 0.8)),
                                  ),
                                  child: const Text(
                                    '取消订单',
                                    style: TextStyle(
                                      height: 1.0,
                                      leadingDistribution:
                                          TextLeadingDistribution
                                              .even, // 设置leading策略
                                    ),
                                  ))
                              : null,
                    ),
                  )
                ],
              ),
            ),
    );
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
